use std::path::Path;

use include_dir::{include_dir, Dir};
use wtask_base::{error::WResult, export::log_debug};
use wtask_file::Response;

use crate::basic::{response_file_data, ResponseBody};


static FILE_HTML: Dir = include_dir!("$CARGO_MANIFEST_DIR/web/dist");


fn get_content_type(file_path: &Path) -> &'static str {
    if let Some(ext) = file_path.extension().and_then(|s| s.to_str()) {
        match ext.to_lowercase().as_str() {
            "ico" => "image/x-icon",
            "html" | "htm" => "text/html",
            "css" => "text/css",
            "js" => "application/javascript",
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "svg" => "image/svg+xml",
            "json" => "application/json",
            "txt" | "log" => "text/plain",
            "pdf" => "application/pdf",
            _ => "application/octet-stream",
        }
    } else {
        "application/octet-stream"
    }
}


pub(crate) fn response_html(uri: &str) -> WResult<Response<ResponseBody>> {
    let uri_raw = format!("{}.gz", uri.trim_start_matches('/'));
    let uri_now = if FILE_HTML.contains(&uri_raw) {
        uri_raw
    } else {
        "index.html".to_owned()
    };
    log_debug!("html: {uri_now}");
    let data = FILE_HTML.get_file(&uri_now).unwrap().contents().to_vec();
    
    let content_type = get_content_type(Path::new(uri_now.trim_end_matches(".gz")));
    response_file_data(
        data,
        uri_now.ends_with(".gz"),
        content_type
    )
}
